import random

from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response
import oauth

import twitter_feeds.views
from . import credentials
from . import models


class TwitterSignInClient(oauth.TwitterClient):

    """Class that uses 'Sign In With Twitter' for OAuth authentication."""

    def get_authorization_url(self):
        """Get the authorization URL for Twitter sign-in."""
        token = self._get_auth_token()
        return "http://twitter.com/oauth/authenticate?oauth_token=%s" % token


def login(request):
    """Redirect the user to Twitter to sign in."""
    client = TwitterSignInClient(*credentials.oauth_args)
    return redirect(client.get_authorization_url())


def oauth_callback(request):
    """Display user details, creating a new account if necessary."""
    client = TwitterSignInClient(*credentials.oauth_args)
    try:
        auth_token = request.REQUEST["oauth_token"]
        auth_verifier = request.REQUEST["oauth_verifier"]
    except KeyError:
        # Not logged in.
        return redirect(reverse(login))
    user_info = client.get_user_info(auth_token, auth_verifier)
    secret = user_info['secret']
    user = models.TwitterUser.all().filter('secret =', secret).get()
    if user is None:
        create_key = True
        while create_key:
            key = []
            for x in xrange(4):
                key.append(str(random.getrandbits(2**5)))
            key = "".join(key)
            create_key = models.TwitterUser.get_by_key_name(key)
        kwargs = {}
        for value in ('username', 'picture', 'token', 'secret'):
            kwargs[value] = user_info[value]
        user = models.TwitterUser(key_name=key, **kwargs)
        user.put()

    info = {'twitter_picture': user.picture, 'twitter_name': user.username}
    feeds = []
    for value in twitter_feeds.views.__dict__.itervalues():
        if hasattr(value, 'type_'):
            feeds.append([value.type_,
                            reverse(value, args=[user.key().name()])])
    info['feeds'] = feeds
    return render_to_response('index.html', info)
